<template>
    <div style="width: 100%;">
        <div class="header-container">
            <!-- 上方导航栏 -->
            <div class="the-header">
                <div class="header-logo" @click="goHome">
                    <svg class="icon">
                        <use xlink:href="#icon-book"></use>
                    </svg>
                    <span>{{ config.WEBSITE_ARTBOARD }}</span>
                </div>
                <!-- 手机端 -->
                <ul
                    v-if="isMobileOrPc"
                    class="navbar"
                    :class="{ show: isMobileOrPc }"
                >
                    <li @click="toggleDayNight()">
                        <div class="sidebar-icon">
                            <template v-if="isDay">
                                <img-icon name="sun" size="2rem" />
                            </template>
                            <template v-else>
                                <img-icon name="moon" size="2rem" />
                            </template>
                        </div>
                    </li>
                    <!-- 搜索 -->
                    <li @click="openSearch">
                        <div class="sidebar-icon">
                            <img-icon name="search" size="2rem" />
                        </div>
                    </li>
                    <!-- 登录 -->
                    <li>
                        <div class="sidebar-icon" @click="openLoginDialog">
                            <img-icon name="user" size="2rem" />
                        </div>
                    </li>
                </ul>
                <!-- 展开图标 -->
                <div
                    v-if="isMobileOrPc"
                    id="open-sidebar"
                    class="open-sidebar"
                    :class="{ unfold: isNavbarVisible }"
                >
                    <img-icon name="unfold" size="3rem" />
                </div>
                <!-- pc端 -->
                <ul v-else class="navbar">
                    <li
                        :class="{ active: item.name == activeName }"
                        v-for="item in navMsg"
                        :key="item.path"
                        @click="goPage(item.path, item.name)"
                    >
                        <img-icon :name="item.icon" size="2rem" class="mr" />
                        <div>
                            {{ item.name }}
                        </div>
                    </li>
                    <li>
                        <div class="header-search">
                            <input
                                type="text"
                                placeholder="搜索文章"
                                @keyup.enter="goSearch()"
                                v-model="keywords"
                            />
                            <div class="search-btn" @click="goSearch()">
                                <svg class="icon">
                                    <use xlink:href="#icon-sousuo"></use>
                                </svg>
                            </div>
                        </div>
                    </li>
                    <li
                        v-show="!loginIn"
                        :class="{ active: item.name == activeName }"
                        v-for="item in loginMsg"
                        :key="item.path"
                        @click="goPage(item.path, item.name)"
                    >
                        <img-icon :name="item.icon" size="2rem" class="mr" />
                        <div>
                            {{ item.name }}
                        </div>
                    </li>
                    <li
                        v-show="loginIn"
                        v-for="(item, index) in menuList"
                        :key="index"
                        @click="goMenuList(item.path)"
                    >
                        <img-icon :name="item.icon" size="2rem" class="mr" />
                        <div>
                            {{ item.name }}
                        </div>
                    </li>
                </ul>
                <div
                    @click="toggleDayNight()"
                    v-if="!isMobileOrPc"
                    class="day-night"
                >
                    <template v-if="isDay">
                        <img-icon name="sun" size="2rem" />
                    </template>
                    <template v-else>
                        <img-icon name="moon" size="2rem" />
                    </template>
                </div>
                <!-- 手机端搜索框 -->
                <el-dialog
                    class="dialog-container"
                    :visible.sync="searchDialogVisible"
                    width="80%"
                    center
                    :fullscreen="true"
                    :modal-append-to-body="false"
                >
                    <!-- 在弹出框中放置搜索框和其他内容 -->
                    <div class="custom-dialog">
                        <div>
                            <el-input
                                v-model="searchKeyword"
                                placeholder="请输入关键字"
                                @input="performSearch"
                            ></el-input>
                        </div>
                        <!-- 其他搜索结果展示区域 -->
                        <!-- 在弹出框中放置搜索框和数据列表 -->
                        <div class="search-results-box">
                            <!-- 使用 el-scrollbar 包装内容，以支持滚动 -->
                            <el-scrollbar wrap-class="search-results-scroll">
                                <div class="search-results">
                                    <div
                                        v-for="(result, index) in searchResults"
                                        :key="index"
                                        class="result-box"
                                    >
                                        <!-- 每个数据在一个方框内，并添加触碰样式 -->
                                        {{ result }}
                                    </div>
                                </div>
                            </el-scrollbar>
                        </div>
                    </div>
                </el-dialog>
                <!-- 侧边栏导航的内容 -->
                <div id="sidebar" class="sidebar">
                    <!-- 控制容器 -->
                    <div class="controls-container">
                        <ul class="tab">
                            <li
                                class="tab-item"
                                :class="{
                                    'controls-active': selectControlValue === 1,
                                }"
                                @click="selectControls(1)"
                            >
                                <div class="controls-text-box">
                                    <img-icon name="catalog" size="2rem" />
                                    <span
                                        class="controls-text"
                                        v-if="selectControlValue === 1"
                                    >
                                        目录
                                    </span>
                                </div>
                            </li>
                            <li
                                class="tab-item"
                                @click="selectControls(2)"
                                :class="{
                                    'controls-active': selectControlValue === 2,
                                }"
                            >
                                <div class="controls-text-box">
                                    <img-icon name="house" size="2rem" />
                                    <span
                                        class="controls-text"
                                        v-if="selectControlValue === 2"
                                    >
                                        我的主页
                                    </span>
                                </div>
                            </li>
                            <li
                                class="tab-item"
                                :class="{
                                    'controls-active': selectControlValue === 3,
                                }"
                                @click="selectControls(3)"
                            >
                                <div class="controls-text-box">
                                    <img-icon name="castle" size="2rem" />
                                    <span
                                        class="controls-text"
                                        v-if="selectControlValue === 3"
                                    >
                                        站点概览
                                    </span>
                                </div>
                            </li>
                        </ul>
                    </div>
                    <!-- 用户容器-->
                    <div class="user-container">
                        <!-- 上半部分：个人信息和头像 -->
                        <div class="profile">
                            <template v-if="loginIn">
                                <img
                                    :src="avator"
                                    alt="Your Avatar"
                                    id="avatar"
                                />
                                <!-- <p class="artboard">Yume Shoka</p> -->
                                <h1 class="title">{{ username }}</h1>
                                <p class="description">{{ introduction }}</p>
                            </template>
                            <template v-else>
                                <div @click="openLoginDialog">
                                    <img
                                        src="@/assets/img/weidenglu.jpg"
                                        alt="Your Avatar"
                                        id="avatar"
                                    />
                                </div>
                            </template>
                        </div>
                        <!-- 下半部分：菜单 -->
                        <div class="sidebar-menu">
                            <ul class="sidebar-menu-navbar">
                                <li
                                    class="align-center"
                                    :class="{
                                        active: item.name === activeName,
                                    }"
                                    v-for="item in phoneNavMsg"
                                    :key="item.path"
                                    @click="goPage(item.path, item.name)"
                                >
                                    <img-icon
                                        :name="item.icon"
                                        size="1.5rem"
                                        class="mr"
                                    />
                                    <div>
                                        {{ item.name }}
                                    </div>
                                </li>
                                <li
                                    v-if="loginIn"
                                    @click="goMenuList(0)"
                                    class="align-center"
                                >
                                    <img-icon
                                        name="logout"
                                        size="1.5rem"
                                        class="mr"
                                    />
                                    <div>退出登录</div>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <!-- 底部进度条-->
                    <div id="progress-bar"></div>
                </div>
                <div id="overlay" class="overlay"></div>
                <!-- 手机端登录框 -->
                <el-dialog
                    class="dialog-container"
                    :visible.sync="loginDialogVisible"
                    :fullscreen="true"
                    width="30%"
                    :before-close="closeLoginAndPassword"
                    :append-to-body="true"
                >
                    <el-form @click="login">
                        <el-form-item model="userInfo" class="mt-5">
                            <el-input
                                v-model="loginInfo.email"
                                placeholder="邮箱"
                            />
                        </el-form-item>
                        <el-form-item
                            model="userInfo"
                            type="password"
                            class="mt-8"
                        >
                            <el-input
                                v-model="loginInfo.password"
                                type="password"
                                show-password
                                placeholder="密码"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button
                                type="primary"
                                @click="login"
                                size="large"
                                class="mx-auto mt-3"
                            >
                                登录
                            </el-button>
                        </el-form-item>
                        <div class="mt-8">
                            <span class="text" @click="openRegisterDialog"
                                >立即注册</span
                            >
                            <span
                                class="text float-right"
                                @click="openForgetPasswordDialog"
                            >
                                忘记密码?
                            </span>
                        </div>
                    </el-form>
                </el-dialog>
                <!-- 手机端注册 -->
                <el-dialog
                    class="dialog-container"
                    :visible.sync="registerDialogVisible"
                    :fullscreen="isMobileOrPc"
                    :before-close="closeLoginAndPassword"
                    :append-to-body="true"
                >
                    <el-form>
                        <el-form-item model="userInfo" class="mt-5">
                            <el-input
                                v-model="loginInfo.username"
                                placeholder="邮箱"
                            />
                        </el-form-item>
                        <el-form-item model="userInfo" class="mt-8">
                            <el-input
                                v-model="loginInfo.code"
                                placeholder="验证码"
                            >
                                <template #append>
                                    <span class="text" @click="sendCode"
                                        >发送</span
                                    >
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item
                            model="userInfo"
                            type="password"
                            class="mt-8"
                        >
                            <el-input
                                v-model="loginInfo.password"
                                type="password"
                                show-password
                                placeholder="密码"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button
                                type="primary"
                                @click="register"
                                size="large"
                                class="mx-auto mt-3"
                            >
                                注册
                            </el-button>
                        </el-form-item>
                        <span class="text" @click="returnLoginDialog"
                            >已有帐号?登录</span
                        >
                    </el-form>
                </el-dialog>
                <!-- 手机端修改密码 -->
                <el-dialog
                    class="dialog-container"
                    :visible="forgetPasswordDialogVisible"
                    :fullscreen="isMobileOrPc"
                    :before-close="closeLoginAndPassword"
                    :append-to-body="true"
                >
                    <el-form>
                        <el-form-item model="userInfo" class="mt-5">
                            <el-input
                                v-model="loginInfo.username"
                                placeholder="邮箱"
                            />
                        </el-form-item>
                        <el-form-item model="userInfo" class="mt-8">
                            <el-input
                                v-model="loginInfo.code"
                                placeholder="验证码"
                            >
                                <template #append>
                                    <span class="text" @click="sendCode"
                                        >发送</span
                                    >
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item
                            model="userInfo"
                            type="password"
                            class="mt-8"
                        >
                            <el-input
                                v-model="loginInfo.password"
                                type="password"
                                show-password
                                placeholder="新密码"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button
                                type="primary"
                                @click="updatePassword"
                                size="large"
                                class="mx-auto mt-3"
                            >
                                确定
                            </el-button>
                        </el-form-item>
                        <span class="text" @click="returnLoginDialog"
                            >返回登录</span
                        >
                    </el-form>
                </el-dialog>

                <!-- pc端登录后的头像 -->
                <!--        <div class="header-right" v-show="loginIn && !isMobileOrPc">-->
                <!--          <div id="user">-->
                <!--            <img :src="avator" />-->
                <!--          </div>-->
                <!--        </div>-->
            </div>
            <div class="brand">
                <div class="pjax">
                    <a href="/" class="logo">
                        <p class="artboard">{{ config.WEBSITE_ARTBOARD }}</p>
                        <h1 class="title">{{ config.WEBSITE_TITLE }}</h1>
                    </a>
                    <p class="meta" itemprop="description">
                        {{ config.WEBSITE_DESCRIPTION }}
                    </p>
                </div>
            </div>
            <!-- 背景图 -->
            <div
                class="header-background"
                :style="{
                    'background-image': 'url(' + currentBackground + ')',
                }"
            ></div>
        </div>
        <DayNightToggle ref="dayNightToggle" style="width: 100%;" />
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import DayNightToggle from "./DayNightToggle.vue";
import ImgIcon from "./ImgIcon.vue";
import { loginMsg, menuList, navMsg, phoneNavMsg } from "@/assets/data/header";
import { isMobileOrPc } from "@/utils/utils";
import {
    getConfig,
    getConfigList,
    getUserInfo,
    loginIn,
    logout,
} from "../api/index";
import _this from "node-notifier";

export default {
    name: "the-header",
    components: {
        DayNightToggle,
        ImgIcon,
    },
    data() {
        return {
            navMsg: [], // 导航栏
            phoneNavMsg: [], // 手机端导航栏
            keywords: "", // 搜索关键字
            loginMsg: [], // 右侧导航栏
            menuList: [], // 用户下拉菜单
            isNavbarVisible: false, // 初始状态为显示
            isMobileOrPc: isMobileOrPc(), // 是否是手机
            // 登录相关
            loginDialogVisible: false,
            registerDialogVisible: false,
            forgetPasswordDialogVisible: false,
            loginInfo: {},
            searchDialogVisible: false, // 展示搜索框
            searchKeyword: "", // 搜索关键字
            searchResults: [], // 搜索结果
            backgroundImages: [
                "https://static.linhaojun.top/aurora/articles/f7963a082ffe11e411b1514e4c35337c.jpg",
            ], // 背景列表
            currentBackground: "", // 当前背景
            config: {
                WEBSITE_DESCRIPTION:
                    "喜欢你的人，会靠近你；不喜欢你的人，会远离你；当然你也不需要跟他们成为朋友。",
                WEBSITE_TITLE: "怎妄想万众瞩目",
                WEBSITE_ARTBOARD: "HOAWAGA",
            },
            isDay: true,
            selectControlValue: 3,
        };
    },
    computed: {
        ...mapGetters([
            "activeName",
            "loginIn",
            "avator",
            "introduction",
            "username",
        ]),
    },
    created() {
        this.navMsg = navMsg;
        this.phoneNavMsg = phoneNavMsg;
        this.loginMsg = loginMsg;
        this.menuList = menuList;
    },
    mounted() {
        // 顶部导航栏的渐变
        window.addEventListener("scroll", function () {
            var header = document.querySelector(".the-header");
            var scrollPosition = window.scrollY;

            // Adjust the threshold as needed
            var threshold = window.innerHeight / 2;

            if (scrollPosition > threshold) {
                header.classList.add("gradient-background");
            } else {
                header.classList.remove("gradient-background");
            }
        });

        // 初始背景图切换
        this.changeBackground();

        // 定时切换背景图（例如，每5秒切换一次）
        this.intervalId = setInterval(() => {
            this.changeBackground();
        }, 3000); // 根据需要更改时间间隔（毫秒为单位）

        // 在手机端需要加载的样式
        if (this.isMobileOrPc) {
            document.querySelector("#avatar").addEventListener(
                "click",
                function (e) {
                    document.querySelector(".sidebar").classList.add("show");
                    e.stopPropagation(); // 关键在于阻止冒泡
                },
                false,
            );
            document.querySelector(".sidebar").addEventListener(
                "click",
                function (e) {
                    e.stopPropagation(); // 点击菜单内部时，阻止事件冒泡，这样，点击内部时，菜单不会关闭
                },
                false,
            );
            document.addEventListener(
                "click",
                function () {
                    document.querySelector(".sidebar").classList.remove("show");
                },
                false,
            );

            // 获取按钮和侧边栏的元素
            const openButton = document.getElementById("open-sidebar");
            const sidebar = document.getElementById("sidebar");
            const overlay = document.getElementById("overlay");

            // 添加点击事件监听器到整个文档
            document.addEventListener("click", (event) => {
                console.log("打开侧边栏...");
                // 检查点击事件是否发生在侧边栏以外的地方
                if (
                    !sidebar.contains(event.target) &&
                    event.target !== openButton
                ) {
                    console.log("打开");
                    // 如果是在侧边栏以外点击，则关闭侧边栏
                    sidebar.style.left = "-25rem"; // 隐藏侧边栏
                    this.isNavbarVisible = false; // 切换状态
                    overlay.style.width = "0";
                    console.log(this.isNavbarVisible);
                }
            });

            // 打开侧边栏
            openButton.addEventListener("click", (event) => {
                event.stopPropagation(); // 阻止点击按钮时事件冒泡到整个文档
                console.log("打开侧边栏...");
                // 关闭
                if (sidebar.style.left === "0rem") {
                    sidebar.style.left = "-25rem"; // 隐藏侧边栏
                    overlay.style.width = "0";
                    this.isNavbarVisible = false; // 切换状态
                    console.log("打开...");
                    // 打开
                } else {
                    console.log("关闭...");
                    overlay.style.width = "100%";
                    sidebar.style.left = "0rem";
                    this.isNavbarVisible = true; // 切换状态
                }
                if (this.loginIn) {
                    this.getUserInfo();
                }
            });

            /*         let touchStartX = 0
let touchEndX = 0

document.addEventListener('touchstart', function(event) {
touchStartX = event.touches[0].clientX
})

document.addEventListener('touchend', function(event) {
touchEndX = event.changedTouches[0].clientX
handleSwipe()
})

document.addEventListener('mousedown', function(event) {
touchStartX = event.clientX
})

document.addEventListener('mouseup', function(event) {
touchEndX = event.clientX
handleSwipe()
})

function handleSwipe() {
const swipeDistance = touchEndX - touchStartX
const threshold = 50 // 设置一个阈值，用于判断滑动距离是否足够认为是左滑

if (swipeDistance < -threshold) {
console.log('左滑')
// 左滑打开菜单栏
if (sidebar.style.left == '0rem') {
sidebar.style.left = '-25rem' // 隐藏侧边栏
overlay.style.width = '0'
this.isNavbarVisible = true // 切换状态
}
} else if (swipeDistance > threshold) {
console.log('右滑')
if (sidebar.style.left != '0rem') {
overlay.style.width = '100%'
sidebar.style.left = '0rem'
this.isNavbarVisible = false
}
}
} */
        }
        // 初始化配置信息
        this.initConfig();
    },
    methods: {
        /**
         * 选择展开的功能
         */
        selectControls(value) {
            this.selectControlValue = value;
            console.log("选择：" + value);
        },
        toggleDayNight() {
            this.isDay = !this.isDay;
            document.body.classList.toggle("day-mode", this.isDay);
            document.body.classList.toggle("night-mode", !this.isDay);
            this.$refs.dayNightToggle.toggleDayNight();
        },
        /**
         * 初始化系统参数
         */
        initConfig() {
            getConfigList([
                "WEBSITE_DESCRIPTION",
                "WEBSITE_TITLE",
                "WEBSITE_ARTBOARD",
            ])
                .then((res) => {
                    console.log(res);
                    let _data = res.data;
                    this.config = { ..._data };
                })
                .catch((err) => {
                    console.log(err);
                });
            getConfig("BACKGROUND_LIST")
                .then((res) => {
                    let _data = res.data;
                    this.backgroundImages = JSON.parse(_data.value);
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        /**
         * 修改背景图（定时器调用）
         */
        changeBackground() {
            const randomIndex = Math.floor(
                Math.random() * this.backgroundImages.length,
            );
            this.currentBackground = this.backgroundImages[randomIndex];
        },
        // 打开搜索框
        openSearch() {
            this.searchDialogVisible = true;
        },
        performSearch() {
            // 在这里执行搜索操作，使用 this.searchKeyword 获取用户输入的关键字
            // 可以发送请求到后台并处理搜索结果
            // 以下示例使用 setTimeout 模拟异步请求
            setTimeout(() => {
                // 模拟搜索结果
                this.searchResults = [
                    "Result 1",
                    "Result 2",
                    "Result 3",
                    "Result 4",
                    "Result 5",
                ];
            }, 500);
        },
        /**
         * 移动端关闭所有展开框
         */
        closeLoginAndPassword() {
            this.loginInfo.code = "";
            this.loginDialogVisible = false;
            this.registerDialogVisible = false;
            this.forgetPasswordDialogVisible = false;
        },
        /**
         * 移动端打开登录框
         */
        openLoginDialog() {
            this.loginDialogVisible = true;
        },
        /**
         * 移动端打开注册框
         */
        openRegisterDialog() {
            this.loginInfo.code = "";
            this.loginDialogVisible = false;
            this.registerDialogVisible = true;
        },
        /**
         * 返回登录
         */
        returnLoginDialog() {
            this.registerDialogVisible = false;
            this.forgetPasswordDialogVisible = false;
            this.loginDialogVisible = true;
        },
        /**
         * 打开忘记密码
         */
        openForgetPasswordDialog() {
            this.loginInfo.code = "";
            this.loginDialogVisible = false;
            this.forgetPasswordDialogVisible = true;
        },
        /**
         * 登录往后台发送请求
         */
        login() {
            let _this = this;
            if (
                this.loginInfo.email.trim().length === 0 ||
                this.loginInfo.password.trim().length === 0
            ) {
                this.notify("邮箱或者密码不能为空", "warning");
                return;
            }
            loginIn({
                email: this.loginInfo.email,
                password: this.loginInfo.password,
            })
                .then((res) => {
                    console.log(res);
                    if (res.code === 1) {
                        _this.notify("登录成功", "success");
                        // 将token存入到LocalStorage
                        localStorage.setItem(
                            "accessToken",
                            res.data.accessToken,
                        );
                        this.getUserInfo();
                    } else {
                        _this.notify("邮箱或密码错误", "error");
                    }
                })
                .catch((err) => {
                    console.log(err);
                    _this.notify("请求异常", "error");
                });
        },
        /**
         * 获取登录用户信息
         */
        getUserInfo() {
            let _this = this;
            getUserInfo()
                .then((res) => {
                    console.log(res);
                    if (res.code === 1) {
                        // 设置状态为已登录
                        _this.$store.commit("setLoginIn", true);
                        _this.$store.commit("setUserId", res.data.id);
                        _this.$store.commit("setUsername", res.data.name);
                        _this.$store.commit("setAvator", res.data.avatar);
                        _this.$store.commit(
                            "setIntroduction",
                            res.data.introduction,
                        );
                        this.loginDialogVisible = false;
                    } else {
                        _this.notify("获取用户信息失败", "error");
                    }
                })
                .catch(() => {
                    _this.notify("获取用户信息失败", "error");
                });
        },
        sendCode() {},
        // 修改密码发送请求
        updatePassword() {},
        //  注册发送请求
        register() {},
        // 提示信息
        notify(title, type) {
            this.$notify({
                title: title,
                type: type,
            });
        },
        /**
         * 跳到主页
         */
        goHome() {
            this.$router.push({ path: "/" });
        },
        /**
         * 上方导航栏菜单点击处理
         */
        goPage(path, name) {
            if (
                !this.loginIn &&
                (path === "/user-info" || path === "/setting")
            ) {
                this.notify("请先登录", "warning");
            } else {
                this.$store.commit("setActiveName", name);
                this.$router.push({ path: path });
                // 关闭侧边栏
                this.closeSidebar();
            }
        },
        closeSidebar() {
            // 获取按钮和侧边栏的元素
            const sidebar = document.getElementById("sidebar");
            const overlay = document.getElementById("overlay");
            sidebar.style.left = "-25rem"; // 隐藏侧边栏
            overlay.style.width = "0";
            this.isNavbarVisible = false; // 切换状态
        },
        /**
         * 跳搜索页
         */
        goSearch() {
            this.$router.push({
                path: "/search",
                query: { keywords: this.keywords },
            });
        },
        // 获取图片地址
        attachImageUrl(srcUrl) {
            return srcUrl
                ? this.$store.state.configure.HOST + srcUrl
                : "../assets/img/user.jpg";
        },
        goMenuList(path) {
            if (path === 0) {
                this.$store.commit("setLoginIn", false);
                this.$store.commit("setIsActive", false);
                logout()
                    .then((res) => {
                        _this.notify("退出登录成功", "success");
                    })
                    .catch((err) => {
                        _this.notify("退出登录失败", "error");
                    });
                this.$router.go(0);
            } else {
                this.$router.push({ path: path });
            }
        },
    },
    beforeDestroy() {
        // 在组件销毁前清除定时器
        clearInterval(this.intervalId);
    },
};
</script>

<style lang="scss" scoped>
@use "../assets/css/the-header.scss";
</style>
